package org.lewis.man.controllers;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lewis.common.Constants;
import org.lewis.common.domain.User;
import org.lewis.common.domain.VCode;
import org.lewis.common.service.UserService;
import org.lewis.common.service.VCodeService;

import com.tocersoft.framework.core.annotations.Controller;
import com.tocersoft.framework.core.annotations.Injection;
import com.tocersoft.framework.web.HttpUtils;
import com.tocersoft.framework.web.WebUtils;
import com.tocersoft.framework.web.annotations.Mapping;
import com.tocersoft.framework.web.annotations.NameSpace;
import com.tocersoft.framework.web.renderer.Renderer;
import com.tocersoft.framework.web.renderer.TemplateRenderer;

/**
 * 账户登录
 * 
 * @author taiqichao
 * 
 */
@Controller
@NameSpace("/accounts")
public class AccountLoginController {

	private final static String VIEWBASEPATH = "/WEB-INF/views/accounts";
	
	/**本地认证保存时间**/
	public final static int cookieSave=24* 60 * 60;

	Log log = LogFactory.getLog(AccountLoginController.class);
	

	@Injection("userService")
	private UserService userService;
	
	@Injection
	private VCodeService vcodeService;

	@Mapping("/login")
	public Renderer login() throws Exception {

		Map<String, Object> model = new HashMap<String, Object>();
		
		String returnUrl=WebUtils.getRequest().getParameter("returnUrl");
		
		if (!WebUtils.isPost()) {
			model.put("returnUrl", returnUrl);
			return new TemplateRenderer(VIEWBASEPATH + "/login.vm",model);
		}

		String email = WebUtils.getRequest().getParameter("form_email");

		String password = WebUtils.getRequest().getParameter("form_password");

		// 非空校验
		if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
			model.put("msg", "请将信息填写完整");
			return new TemplateRenderer(VIEWBASEPATH + "/login.vm",model);
		}

		// 认证用户
		User user = userService.getUserByEmailAndPwd(email, password);

		// 认证失败
		if (user == null) {
			model.put("msg", "用户名密码错误");
			return new TemplateRenderer(VIEWBASEPATH + "/login.vm",model);
		}

		// 未激活状态
		if (user.getStatus() == 0) {
			model.put("msg", "账户未激活，请去邮箱(" + email + ")激活您的账户。");
			return new TemplateRenderer(VIEWBASEPATH + "/login.vm",model);
		}
		
		// 禁用状态
		if (user.getStatus() == 2) {
			model.put("msg", "该账户被管理员禁用！");
			return new TemplateRenderer(VIEWBASEPATH + "/login.vm",model);
		}

		String remember = WebUtils.getRequest().getParameter("remember");
		if ("true".equals(remember)) {// 下次自动登录
			//剔除上次的code
			VCode vcode=vcodeService.getByCode(user.getId(),VCode.TYPE.AUTOLOGIN.name());
			if(null!=vcode){
				vcodeService.removeCode(vcode.getId());
			}
			//重新生成一个code
			vcode=new VCode();
			vcode.setCode(DigestUtils.md5Hex(UUID.randomUUID().toString()));
			vcode.setType(VCode.TYPE.AUTOLOGIN.name());
			vcode.setUid(user.getId());
			vcodeService.addVCode(vcode);
			//客户端加cookie
			HttpUtils.setCookie(Constants.CLIENTAUTHCOOKIEKEY, vcode.getCode(), cookieSave);
		}else{//下次不自动登录
			//剔除code
			VCode vcode=vcodeService.getByCode(user.getId(),VCode.TYPE.AUTOLOGIN.name());
			if(null!=vcode){
				vcodeService.removeCode(vcode.getId());
			}
			//移除客户端cookie
			HttpUtils.removeCookie(Constants.CLIENTAUTHCOOKIEKEY);
		}
		
		WebUtils.getSession().setAttribute(Constants.CURRENTUSER, user);
		
		if(StringUtils.isNotEmpty(returnUrl)){
			WebUtils.getResponse().sendRedirect(HttpUtils.getContentPath()+returnUrl);
		}else{
			WebUtils.getResponse().sendRedirect(HttpUtils.getContentPath());
		}
		return null;
	}

}
